//
//  UICollectionViewCell+BNAdd.m
//  BNCodeGuide
//
//  Created by kevin007 on 2021/5/20.
//  Copyright © 2021 kevin007. All rights reserved.
//

#import "UICollectionViewCell+BNAdd.h"

@implementation UICollectionViewCell (BNAdd)
/** 从xib加载cell，自动复用 */
+ (instancetype)cellFromXibWithCollectionView:(UICollectionView *)collectionView forIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = self.reusedId;
    NSMutableSet *identifierSet = [self setCellIdentifierSetForCollectionView:collectionView];
    
    if (![identifierSet containsObject:identifier]) {
        NSLog(@"register nib cell");
        [collectionView registerNib:[UINib nibWithNibName:identifier bundle:nil] forCellWithReuseIdentifier:identifier];
        [identifierSet addObject:identifier];
    }
    
    return [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
}

/** 加载纯代码cell，自动复用 */
+ (instancetype)cellFromClassWithCollectionView:(UICollectionView *)collectionView forIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = self.reusedId;
    NSMutableSet *identifierSet = [self setCellIdentifierSetForCollectionView:collectionView];
    
    if (![identifierSet containsObject:identifier]) {
        NSLog(@"register class cell");
        [collectionView registerClass:[self class] forCellWithReuseIdentifier:identifier];
        [identifierSet addObject:identifier];
    }
    
    return [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
}

/** 关联 IdentifierSet*/
+ (NSMutableSet *)setCellIdentifierSetForCollectionView:(UICollectionView *)collectionView {
    if (![collectionView getAssociatedValueForKey:_cmd]) {
        NSMutableSet *identifierSet = [[NSMutableSet alloc] init];
        [collectionView setAssociateValue:identifierSet withKey:_cmd];
        return identifierSet;
    }
    
    return [collectionView getAssociatedValueForKey:_cmd];
}
@end
